import { prisma } from '../../utils/prisma'
import { getUserIdOrThrow } from '../../utils/guard'
import { z } from 'zod'

const bodySchema = z.object({
  name: z.string().min(1),
  birthday: z.string().optional(),
  avatarUrl: z.string().url().optional()
})

export default eventHandler(async (event) => {
  const userId = getUserIdOrThrow(event)
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const { name, birthday, avatarUrl } = parsed.data
  const child = await prisma.child.create({
    data: {
      userId,
      name,
      birthday: birthday ? new Date(birthday) : null,
      avatarUrl
    }
  })
  return { child }
})


